
import getLasetEvent from '../utils/getLastEvent'
import getSelector from '../utils/getSelector'
import tracker from '../utils/tracker'
export function injectJsError(){
  // 通过啊监听error错误事件捕获报错信息
  window.addEventListener('error',event=>{
    console.log(event)
    let lastEvent = getLasetEvent()
   
    // 资源加载错误
    if(event.target && (event.target.src || event.target.href)){
      tracker.send({
        kind:'stability',
        type:"error",
        errorType:"resourceError",
        filename:event.target.src || event.target.href,
        tagName:event.target.tagName, // 标签名
        timeStamp:fromTime(event.timeStamp),// 时间
        selector:getSelector(event.path || event.target)
      })
    }else {
      //  console.log(lastEvent.path)
      // 分为资源加载错误或者代码执行错误
    tracker.send({
        "kind": "stability",//大类
        "type": "error",//小类
        "errorType": "jsError",//错误类型
        "message":event.message,//类型详情
        "filename": event.filename,//访问的文件名
        "position": `${event.lineno}:${event.colno}`,//行列信息
        "stack": getLines(event.error.stack),//堆栈信息
        "selector": lastEvent ? getSelector(lastEvent.path) : ''//选择器
    })
    }
    
  },true) // true代表在捕获阶段调用,false代表在冒泡阶段捕获,使用true或false都可以
  // promise如果没有写捕获代码，走这个监听函数
  window.addEventListener('unhandledrejection',event=>{
    let lasteEvent = getLasetEvent()
    let message = ''
    let line = 0
    let column = 0
    let file = ''
    let stack = ''
    if(typeof event.reason === 'string'){
      // 如果是reject抛出的错误为文本
      message = event.reason
    }else if(typeof event.reason === 'object'){
      message = event.reason.message
    }
    let reason = event.reason
    if(typeof reason === 'object'){
      if(reason.stack){
        // 堆栈信息存在的话
        const matchResult = reason.stack.match(/at\s+(.+):(\d+):(\d+)/);
        if (matchResult) {
            file = matchResult[1];
            line = matchResult[2];
            column = matchResult[3];
        }
        stack = getLines(reason.stack);
      }
    }
    tracker.send({//未捕获的promise错误
        kind: 'stability',//稳定性指标
        type: 'error',//jsError
        errorType: 'promiseError',//unhandledrejection
        message: message,//标签名
        filename: file,
        position: line + ':' + column,//行列
        stack,
        selector: lasteEvent ? getSelector(lasteEvent.path || lasteEvent.target) : ''
    })
  },true)
}

function getLines(stack){
  if(!stack) return
  return stack.split('\n').slice(1).map(item=>item.replace(/^\s+at\s+/g,"")).join('^')
}

function fromTime(time){
  return `${time}`.split(".")[0]
}